package com.dawn.java.thread.jdk;


import java.lang.reflect.Field;
import sun.misc.Unsafe;

/**
 * @author Ruffianjiang
 * @version V1.0
 * @Title: Thread
 * @Package java4learn
 * @date 2019/8/19 23:09
 */
public class Thread {
    /**
     * 参考
     * https://blog.csdn.net/zhoufanyang_china/article/details/86750351
     * https://www.cnblogs.com/zzq6032010/p/11368318.html
     */

    static final Unsafe unsafe = getUnsafe();
    static final boolean is64bit = true; // auto detect if possible.

    public static void main(String... args) {
        ModelUser a = new ModelUser();

        //GC前
        System.out.println("-----------GC前------------");
        print(a);

        System.gc();

        //GC后
        System.out.println("-----------GC后------------");
        print(a);
    }

    private static void print(ModelUser a) {
        // hashcode
        System.out.println("Hashcode :       " + a.hashCode());
        System.out.println("Hashcode :       " + System.identityHashCode(a));
        System.out.println("Hashcode (HEX) : " + Integer.toHexString(a.hashCode()));// Integer.toHexString(int)是将一个整型转成一个十六进制数

        // toString
        System.out.println("toString :       " + String.valueOf(a));

        //通过sun.misc.Unsafe;
        printAddresses("Address", a);
    }

    @SuppressWarnings("deprecation")
    public static void printAddresses(String label, Object... objects) {
        System.out.print(label + ":         0x");
        long last = 0;
        int offset = unsafe.arrayBaseOffset(objects.getClass());
        int scale = unsafe.arrayIndexScale(objects.getClass());
        switch (scale) {
            case 4:
                long factor = is64bit ? 8 : 1;
                final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor;
                System.out.print(Long.toHexString(i1));
                last = i1;
                for (int i = 1; i < objects.length; i++) {
                    final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor;
                    if (i2 > last)
                        System.out.print(", +" + Long.toHexString(i2 - last));
                    else
                        System.out.print(", -" + Long.toHexString(last - i2));
                    last = i2;
                }
                break;
            case 8:
                throw new AssertionError("Not supported");
        }
        System.out.println();
    }

    private static Unsafe getUnsafe() {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(null);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }


}
